package author

import (
	// "log"
	"net/http"
	"poetry/database"
	"poetry/model"
	"strconv"

	"github.com/gin-gonic/gin"
)

// GetAuthorList 查找所有作者
func GetAuthorList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))

	var authors []model.Author
	var count int

	database.DB.Model(&model.Author{}).Count(&count).Limit(10).Offset((page - 1) * 10).Find(&authors)
	// database.DB.Model(&model.Author{}).Count(&count).Find(&authors)

	var result = make([]model.AuthorSerializer, len(authors))

	for index, author := range authors {
		result[index] = author.Serializer()
	}
	// claims, _ := c.Get("claims")
	c.JSON(http.StatusOK, gin.H{
		"code"  : 0,
		"data"  : gin.H{
			"list"  : result,
			"total" : count,
			"page"  : page,
		},
	})
}

// GetAuthorDetail 查找作者详情
func GetAuthorDetail(c *gin.Context) {
	if id := c.Query("id"); id == "" {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"msg": "ID不能为空",
			"id": id,
		})
		return
	} else {
		var author model.Author
		if err := database.DB.Where("id = ?", id).First(&author).Error; err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    -1,
				"msg": "请输入正确的ID",
				"id": id,
			})
			return
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code":    0,
				"data": author.Serializer(),
			})
			return
		}
	}
}

type Update struct {
	ID      int `form:"id" json:"id" binding:"required"`
	Profile string `form:"profile" json:"profile" binding:"required"`
}

func GetAuthorUpdate(c *gin.Context) {
	var update Update
	if err := c.ShouldBindJSON(&update); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"msg": "参数不能为空",
		})
	} else {
		var author model.Author
		if err := database.DB.Where("id = ?", update.ID).First(&author).Error; err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    -1,
				"msg": "请输入正确的ID",
			})
			return
		} else {
			// database.DB.Save(&author)
			database.DB.Model(&author).Update(update)
			c.JSON(http.StatusOK, gin.H{
				"code":    0,
				"msg": "修改成功",
			})
			return
		}
	}
}
